/**
 * Created by WLG on 2018/11/9.
 */
let ChatBusinessService = require("../services/chatBusinessService");
let ChatMemInfoService = require("../services/chatMemInfoService");
let ChatService = require("../services/chatService");
let serverConfig = require('../config/serverConfig');
let SystemConst = require('../config/systemConst');
let Router = require('koa-router');
let join = require('path').join;
let SocketPushService = require('../services/socketPushService');

class ChatMsgWebHandler {
    static attach(app,io){
        let router = new Router();
        router
            .get([serverConfig.httpNameSpace,"chatList"].join("/") , async (ctx, next) => {
                ctx.set("Content-Type", "application/json");
                let param = ctx.query;
                ctx.response.body = await ChatBusinessService.searchChatAndChatMemByMemId(param.memId,param.lastTime);
                await next();
            })
            .get([serverConfig.httpNameSpace,"chatMsgList"].join("/") , async (ctx, next) => {
                ctx.set("Content-Type", "application/json");
                let param = ctx.query;
                ctx.response.body = await ChatBusinessService.getChatMsgDetail(param.memId,param.chatId,param.sortId);
                await ChatMemInfoService.updateChatMemInfoReadState(param.memId,param.chatId);
                await next();
            })
            .get([serverConfig.httpNameSpace,"searchAccountMem"].join("/") , async (ctx, next) => {
                ctx.set("Content-Type", "application/json");
                let param = ctx.query;
                ctx.response.body = await ChatBusinessService.searchAccountMem(param.name);
                await next();
            })
            .get([serverConfig.httpNameSpace,"searchGroupFile"].join("/") , async (ctx, next) => {
                ctx.set("Content-Type", "application/json");
                let param = ctx.query;
                ctx.response.body = await ChatBusinessService.searchGroupFile(param.chatID);
                await next();
            })
            .get([serverConfig.httpNameSpace,"withdrawMsg"].join("/") , async (ctx, next) => {
                ctx.set("Content-Type", "application/json");
                let param = ctx.query;
                let lastChatMsg = await ChatBusinessService.withdrawMsg(param.chatID , param.chatMsgID);
                await SocketPushService.pushWithdrawMsg(io,param.chatID , param.chatMsgID ,lastChatMsg);
                ctx.response.body = lastChatMsg;
                await next();
            })
            /**
             * 创建会话 判断是否存在当前mem组合的聊天 有则返回旧聊天 设置 isOld 参数
             */
            .post([serverConfig.httpNameSpace,"createChat"].join("/") , async (ctx, next) => {
                ctx.set("Content-Type", "application/json");
                let param =  ctx.request.body;
                let memArray = param.mem;
                let isUnique = param.isUnique;
                let chatMemsSha1 = param.uniqueId;
                //如果是 单人 聊天 也设置为单独会话
                if( SystemConst.ChatType.ChatSingle == param.chatType && memArray.length == 2 ){
                    chatMemsSha1 = memArray.sort().join('-');
                    isUnique = true;
                }
                let tempChat = null;

                if(isUnique){
                    tempChat = await ChatService.loadByMemsSha1(chatMemsSha1);
                }

                if(!tempChat){
                    param.memsSha1 = chatMemsSha1;
                    tempChat = await ChatBusinessService.createChat(param);
                    let currentTime = new Date().getTime();
                    memArray.forEach(async item =>{
                        let chatMemInfoTemp = {
                            memID:  item,
                            chatID: tempChat._id,
                            lastReadTime: currentTime,
                            unReadSize: "0",
                            joinTime: currentTime,
                            status: "1",
                        };
                        await ChatMemInfoService.save(chatMemInfoTemp);
                    });
                }
                ctx.response.body = await ChatBusinessService.getChatMsgDetail(param.creator,tempChat._id,null);
                await next();
            });

        app.use(router.routes()).use(router.allowedMethods());

        commonUtil.consoleSysInfo("WebHandler初始化完成");
    };
}
module["exports"] = ChatMsgWebHandler;